package com.wuzhen.wzzt.controller;

import com.wuzhen.wzzt.core.converter.WxMappingJackson2HttpMessageConverter;
import com.wuzhen.wzzt.core.ret.RetCode;
import com.wuzhen.wzzt.core.ret.RetResponse;
import com.wuzhen.wzzt.core.ret.RetResult;
import com.wuzhen.wzzt.model.AuthInfo;
import com.wuzhen.wzzt.model.WxLoginResultDto;
import com.wuzhen.wzzt.service.RedisService;
import com.wuzhen.wzzt.vo.WxLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


//  登录注册信息 样例
//  http://www.demodashi.com/demo/12736.html

@RestController
@RequestMapping
@Api(tags = {"请求微信获取open_id接口"}, description = "WxLoginController", position = 1)
public class WxLoginController {
    private Logger logger = LoggerFactory.getLogger(WxLoginController.class);

    private String wxAuthUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    final String appId = "wxeb6b46d7e7662f62";
    //wxff39e92644997dd0

    final String appsecret = "40e139196e380cc42f8f8f2d2bfba2a8";
    //768c9d53f4b1b0f5f34e93507d248323

    /**
     * 服务器第三方session有效时间，单位秒, 默认30天
     */
    private static final Long EXPIRES = 30 * 86400L;


    @Resource
    private RedisService redisService;

    @Autowired
    RestTemplate restTemplate;


    @PostMapping("/wxlogin")
    @ApiOperation(value = "获取open_id接口", notes = "根据code请求微信获取open_id,返回前端token")
    public RetResult<AuthInfo> login(@RequestBody WxLoginVo wxLoginVo) {
        logger.info("获取open_id接口，前端请求入参:code：{}", wxLoginVo.getCode());

        String url = String.format(wxAuthUrl, appId, appsecret, wxLoginVo.getCode());

        restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());

        WxLoginResultDto wxLoginResultDto = restTemplate.getForObject(url, WxLoginResultDto.class);

        logger.info("请求code：{}微信返回结果：{}", wxLoginVo.getCode(), wxLoginResultDto.toString());

        if (wxLoginResultDto.getErrcode() != null && !wxLoginResultDto.getErrcode().equals("0")) {
            logger.error("wx login failed, errCode: [{}], errMsg: [{}]", wxLoginResultDto.getErrcode(), wxLoginResultDto.getErrmsg());
            return RetResponse.makeRsp(RetCode.WX_UNAUTHORIZED.code, wxLoginResultDto.getErrcode() + "_" + wxLoginResultDto.getErrmsg());
        }
        String thirdSessionKey = create3rdSession(wxLoginResultDto.getOpenid(), wxLoginResultDto.getSession_key(), EXPIRES);
        AuthInfo authInfo = new AuthInfo();
        authInfo.setThirdSessionKey(thirdSessionKey);
        logger.info("请求code：{}返回前端token结果：{}", wxLoginVo.getCode(), authInfo.toString());
        return RetResponse.makeOKRsp(authInfo);
    }


    private String create3rdSession(String wxOpenId, String wxSessionKey, Long expires) {
        String thirdSessionKey = RandomStringUtils.randomAlphanumeric(64);
        StringBuffer sb = new StringBuffer();
        sb.append(wxSessionKey).append("#").append(wxOpenId);
        redisService.set(thirdSessionKey, sb.toString());
        redisService.expire(thirdSessionKey, expires);
        return thirdSessionKey;
    }


}

